package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.query.StrategyCommentQueryObject;
import cn.wolfcode.trip.base.query.TravelQueryObject;
import cn.wolfcode.trip.base.service.IStrategyCommentService;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//用户资源控制器
@RestController
@RequestMapping("users")
public class UserController {
    //关联service
    @Autowired
    private IUserService userService;

    @Autowired
    private ITravelService travelService;

    @Autowired
    private IStrategyCommentService strategyCommentService;

    //用户注册的方法
    @PostMapping
    public JSONResult register(User user){
        JSONResult json=new JSONResult();
        try {
           userService.saveOrUpdate(user);
        } catch (Exception e) {
            e.printStackTrace();
            json.mark(e.getMessage());
        }
        return json;
    }

    @PutMapping("{id}")
    public JSONResult update(User user){
        userService.saveOrUpdate(user);
        //把更新后的对象重新传到页面
        return new JSONResult().setResult(user);
    }

    @GetMapping("{authorId}/travels")
    public PageInfo queryTravels(TravelQueryObject qo){
        qo.setOrderby("t.lastUpdateTime desc");
        return travelService.queryForList(qo);
    }

    @GetMapping("{id}")
    public User query(@PathVariable("id") Long id){
        return userService.queryById(id);
    }

    @GetMapping
    public JSONResult queryAll(){
        List<User> users = userService.queryAll();
        JSONResult json = new JSONResult();
        json.setResult(users);
        return json;
    }

    @GetMapping("{authorId}/comments")
    public PageInfo queryComments(StrategyCommentQueryObject qo){//方便直接将{}里的内容封装进qo里
        qo.setOrderby("sc.createTime desc");
       return strategyCommentService.query(qo);
    }

}
